import React, { useEffect, useState } from 'react';
import { Modal, Descriptions, Image, Tag, Tabs, Table, Progress, Button, Space, Statistic, Row, Col, Card } from 'antd';
import { CalendarOutlined, UserOutlined, TrophyOutlined, DollarOutlined } from '@ant-design/icons';
import { getActivityDetail, getActivityParticipants } from '@/services/contentManagementApi';
import moment from 'moment';

interface ActivityDetailProps {
  visible: boolean;
  activity?: CONTENT.ActivityModel;
  onCancel: () => void;
}

const ActivityDetail: React.FC<ActivityDetailProps> = ({ visible, activity, onCancel }) => {
  const [loading, setLoading] = useState(false);
  const [activityDetail, setActivityDetail] = useState<CONTENT.ActivityModel | null>(null);
  const [participants, setParticipants] = useState<any[]>([]);

  useEffect(() => {
    if (visible && activity) {
      loadActivityData();
    }
  }, [visible, activity]);

  const loadActivityData = async () => {
    if (!activity) return;
    
    setLoading(true);
    try {
      const [detailRes, participantsRes] = await Promise.all([
        getActivityDetail(activity.id),
        getActivityParticipants(activity.id, { limit: 10 }),
      ]);

      setActivityDetail(detailRes.data);
      setParticipants(participantsRes.data?.list || []);
    } catch (error) {
      console.error('加载活动数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!activity) return null;

  const displayActivity = activityDetail || activity;

  // 状态标签颜色映射
  const statusColorMap = {
    draft: 'default',
    published: 'green',
    ended: 'orange',
    cancelled: 'red',
  };

  // 活动类型标签颜色映射
  const typeColorMap = {
    promotion: 'blue',
    competition: 'purple',
    festival: 'orange',
    learning: 'green',
  };

  // 状态映射
  const statusMap = {
    draft: '草稿',
    published: '进行中',
    ended: '已结束',
    cancelled: '已取消',
  };

  // 类型映射
  const typeMap = {
    promotion: '推广活动',
    competition: '竞赛活动',
    festival: '节日活动',
    learning: '学习活动',
  };

  // 参与者表格列
  const participantColumns = [
    {
      title: '参与者',
      key: 'participant',
      render: (record: any) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <img
            src={record.avatar}
            alt={record.nickname}
            style={{ width: 32, height: 32, borderRadius: '50%' }}
          />
          <div>
            <div>{record.nickname}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>@{record.username}</div>
          </div>
        </div>
      ),
    },
    {
      title: '参与时间',
      dataIndex: 'joined_at',
      key: 'joined_at',
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '完成状态',
      dataIndex: 'completion_status',
      key: 'completion_status',
      render: (status: string) => {
        const statusMap = {
          pending: { text: '进行中', color: 'processing' },
          completed: { text: '已完成', color: 'success' },
          failed: { text: '未完成', color: 'error' },
        };
        const config = statusMap[status as keyof typeof statusMap] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '得分',
      dataIndex: 'score',
      key: 'score',
      render: (score: number) => score || '-',
    },
  ];

  // 计算活动进度
  const getActivityProgress = () => {
    const now = moment();
    const start = moment(displayActivity.start_time);
    const end = moment(displayActivity.end_time);
    
    if (now.isBefore(start)) return 0;
    if (now.isAfter(end)) return 100;
    
    const total = end.diff(start);
    const elapsed = now.diff(start);
    return Math.round((elapsed / total) * 100);
  };

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <div>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={8}>
              <Image
                src={displayActivity.cover_image}
                alt={displayActivity.title}
                width="100%"
                style={{ borderRadius: 8 }}
                fallback=""
              />
            </Col>
            <Col span={16}>
              <Descriptions column={1} bordered>
                <Descriptions.Item label="活动标题">{displayActivity.title}</Descriptions.Item>
                <Descriptions.Item label="副标题">{displayActivity.subtitle || '-'}</Descriptions.Item>
                <Descriptions.Item label="活动类型">
                  <Tag color={typeColorMap[displayActivity.type]}>
                    {typeMap[displayActivity.type]}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={statusColorMap[displayActivity.status]}>
                    {statusMap[displayActivity.status]}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="报名费用">
                  {displayActivity.registration_fee > 0 ? `¥${displayActivity.registration_fee}` : '免费'}
                </Descriptions.Item>
                <Descriptions.Item label="活动进度">
                  <Progress percent={getActivityProgress()} />
                </Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>

          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="参与人数"
                  value={displayActivity.participant_count || 0}
                  prefix={<UserOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="完成人数"
                  value={Math.round((displayActivity.participant_count || 0) * (displayActivity.completion_rate || 0))}
                  prefix={<TrophyOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="完成率"
                  value={Math.round((displayActivity.completion_rate || 0) * 100)}
                  suffix="%"
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="报名费收入"
                  value={(displayActivity.participant_count || 0) * (displayActivity.registration_fee || 0)}
                  prefix={<DollarOutlined />}
                  suffix="元"
                />
              </Card>
            </Col>
          </Row>

          <Descriptions column={1} bordered>
            <Descriptions.Item label="活动简介">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayActivity.description}</div>
            </Descriptions.Item>
            <Descriptions.Item label="活动详情">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayActivity.content || '-'}</div>
            </Descriptions.Item>
            <Descriptions.Item label="活动规则">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayActivity.rules || '-'}</div>
            </Descriptions.Item>
            <Descriptions.Item label="奖励说明">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayActivity.rewards || '-'}</div>
            </Descriptions.Item>
            <Descriptions.Item label="联系方式">
              <div style={{ whiteSpace: 'pre-wrap' }}>{displayActivity.contact_info || '-'}</div>
            </Descriptions.Item>
            <Descriptions.Item label="开始时间">
              {moment(displayActivity.start_time).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="结束时间">
              {moment(displayActivity.end_time).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {moment(displayActivity.created_at).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              {moment(displayActivity.updated_at).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="外部链接">
              {displayActivity.external_url ? (
                <a href={displayActivity.external_url} target="_blank" rel="noopener noreferrer">
                  {displayActivity.external_url}
                </a>
              ) : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="活动标签">
              {displayActivity.tags && displayActivity.tags.length > 0 ? (
                <Space wrap>
                  {displayActivity.tags.map((tag, index) => (
                    <Tag key={index}>{tag}</Tag>
                  ))}
                </Space>
              ) : '-'}
            </Descriptions.Item>
          </Descriptions>
        </div>
      ),
    },
    {
      key: 'participants',
      label: '参与者列表',
      children: (
        <Table
          columns={participantColumns}
          dataSource={participants}
          rowKey="user_id"
          pagination={false}
          loading={loading}
          size="small"
        />
      ),
    },
    {
      key: 'settings',
      label: '活动设置',
      children: (
        <Descriptions column={2} bordered>
          <Descriptions.Item label="最大参与人数">
            {displayActivity.max_participants || '不限制'}
          </Descriptions.Item>
          <Descriptions.Item label="最少参与人数">
            {displayActivity.min_participants || '无要求'}
          </Descriptions.Item>
          <Descriptions.Item label="是否推荐">
            {displayActivity.is_featured ? '是' : '否'}
          </Descriptions.Item>
          <Descriptions.Item label="允许提前结束">
            {displayActivity.allow_early_end ? '是' : '否'}
          </Descriptions.Item>
          <Descriptions.Item label="自动审核">
            {displayActivity.auto_approve ? '是' : '否'}
          </Descriptions.Item>
          <Descriptions.Item label="发送通知">
            {displayActivity.send_notifications ? '是' : '否'}
          </Descriptions.Item>
          <Descriptions.Item label="排序权重">
            {displayActivity.sort_order || 0}
          </Descriptions.Item>
        </Descriptions>
      ),
    },
  ];

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <CalendarOutlined style={{ fontSize: 20 }} />
          <div>
            <div>{displayActivity.title}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>活动详情</div>
          </div>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
      ]}
      width={1000}
      destroyOnClose
    >
      <Tabs items={tabItems} />
    </Modal>
  );
};

export default ActivityDetail;
